package com.example.micro.netty.server.tcpprotocal;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * tcp粘包拆包 server-handler
 *
 * @author Code Farmer
 * @create 2021/3/7 7:07 下午
 */
public class MyTcpProtocalServerHandler extends SimpleChannelInboundHandler<MessageProtocal> {

    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocal messageProtocal) throws Exception {
        int len = messageProtocal.getLen();
        byte[] content = messageProtocal.getContent();

        System.out.println("服务其接收到信息如下：");
        System.out.println("长度：" + len);
        System.out.println("内容：" + new String(content, StandardCharsets.UTF_8));

        System.out.println("服务器接收到消息包数量=" + ++this.count);

        String responseContent = UUID.randomUUID().toString();
        int responseLen = responseContent.getBytes(StandardCharsets.UTF_8).length;
        //构建一个协议包
        MessageProtocal responseMessage =
                new MessageProtocal(responseLen, responseContent.getBytes(StandardCharsets.UTF_8));

        channelHandlerContext.writeAndFlush(responseMessage);
    }

    /**
     * 异常处理
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
